package com.example.news.fragment;

import android.content.res.ColorStateList;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.LinearInterpolator;
import android.view.animation.TranslateAnimation;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.example.news.R;
import com.example.news.bean.TypeDb;
import com.example.news.bean.TypeJson;
import com.example.news.dao.TypeDao;
import com.example.news.utils.RotateDownPageTransformer;
import com.google.gson.Gson;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

import java.util.ArrayList;

/**
 * Created by Administrator on 2016/5/17.
 */
public class HomeFragment extends Fragment {
    private ArrayList<TypeJson.MyData> list;
    private RadioGroup group;
    private ViewPager viewPager;
    private String mPath;
    private TypeDao dao;
    private HorizontalScrollView lable;
    private int currentIndicatorLeft = 0;
    private int indicatorWidth;
    private ArrayList<Fragment> frag;
    private LayoutInflater mInflater;
    private RadioButton radioButton;
    private ImageView iv_nav_indicator;
    private ImageView add;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        //找到布局文件
        View view = inflater.inflate(R.layout.home_frag, null);
        //找控件
        group = (RadioGroup) view.findViewById(R.id.tab_group);
        lable = (HorizontalScrollView) view.findViewById(R.id.lable);
        viewPager = (ViewPager) view.findViewById(R.id.home_viewPager);
        iv_nav_indicator = (ImageView) view.findViewById(R.id.iv_nav_indicator);
        add = (ImageView) view.findViewById(R.id.add);

        dao = new TypeDao(getActivity());

        //得到数据
        getData();

        frag = getFrag();

        //初始化头部选项卡
        initView();

        //设置缓存页数，避免ViewPager中切换界面Fragment被销毁的问题
        viewPager.setOffscreenPageLimit(11);

        /**
         * 给viewpager设置滑动监听
         */
        viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                if (group != null && group.getChildCount() > position) {
                    ((RadioButton) group.getChildAt(position)).performClick();
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }

        });
        /**
         * 单选按钮监听
         */
        group.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (group.getChildAt(checkedId) != null) {
                    TranslateAnimation animation = new TranslateAnimation(
                            currentIndicatorLeft,
                            ((RadioButton) group.getChildAt(checkedId)).getLeft(), 0f, 0f);
                    animation.setInterpolator(new LinearInterpolator());
                    animation.setDuration(100);
                    animation.setFillAfter(true);

                    //执行位移动画
                    iv_nav_indicator.startAnimation(animation);
                    viewPager.setCurrentItem(checkedId);
                    lable.smoothScrollTo(
                            (checkedId > 1 ? ((RadioButton) group.getChildAt(checkedId)).getLeft() : 0) - ((RadioButton) group.getChildAt(2)).getLeft(), 0);
                }
            }
        });

        // 设置切换动画
        //viewPager.setPageTransformer(true, new DepthPageTransformer());
        viewPager.setPageTransformer(true, new RotateDownPageTransformer());

        //频道管理
        add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(getActivity(), "频道管理", Toast.LENGTH_SHORT).show();

            }
        });

        return view;
    }

    /*
     * 定义请求网络的方法
     */
    public void getData() {
        new Thread() {
            public void run() {
                HttpUtils utils = new HttpUtils();
                utils.send(HttpRequest.HttpMethod.GET, "http://169.254.25.59:8080/yidian/json/type.json", new RequestCallBack<String>() {

                    @Override
                    public void onFailure(HttpException arg0, String arg1) {

                        ArrayList<TypeDb> lists = dao.query();

                        //清空group里面的控件
                        group.removeAllViews();
                        //动态添加标签
                        for (int i = 0; i < lists.size(); i++) {
                            //创建一个标签按钮
                            radioButton = new RadioButton(getActivity());
                            //设置id
                            radioButton.setId(lists.get(i).getId());
                            if (i == 0) {
                                radioButton.setChecked(true);
                            } else {
                                radioButton.setChecked(false);
                            }
                            //设置小圆点图标
                            radioButton.setButtonDrawable(R.color.btn);
                            //设置间距
                            radioButton.setPadding(10, 5, 10, 5);
                            //设置选择状态颜色
                            ColorStateList colorList = getResources().getColorStateList(R.color.radio_backgroud);
                            radioButton.setTextColor(colorList);
                            //设置字体大小
                            radioButton.setTextSize(20);
                            //设置文本内容
                            radioButton.setText(lists.get(i).getName());
                            //将控件放进group里面
                            group.addView(radioButton);
                        }
                        group.invalidate();

                        //连接失败时
                        Toast.makeText(getActivity(), "当前网络不可用", Toast.LENGTH_SHORT).show();

                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        //连接成功，得到数据
                        String json = responseInfo.result;
                        Gson gson = new Gson();
                        TypeJson typeJson = gson.fromJson(json, TypeJson.class);
                        list = typeJson.data;

                        dao.del();//删除数据库的数据
                        dao.add(list);//将网络获取的数据添加的数据库

                        addTal();
                    }
                });
            }
        }.start();
    }

    /**
     * 定义添加标签的方法
     */
    public void addTal() {
        //清空group里面的控件
        group.removeAllViews();
        //动态添加标签
        for (int i = 0; i < list.size(); i++) {
            //创建一个标签按钮
            radioButton = (RadioButton) mInflater.inflate(R.layout.radio, null);
            //设置id
            radioButton.setId(i);
            if (i == 0) {
                radioButton.setChecked(true);
            } else {
                radioButton.setChecked(false);
            }
            radioButton.setLayoutParams(new ViewGroup.LayoutParams(indicatorWidth, ViewGroup.LayoutParams.MATCH_PARENT));
            //设置小圆点图标
            radioButton.setButtonDrawable(R.color.btn);
            //设置间距
            radioButton.setPadding(10, 5, 10, 5);
            //设置选择状态颜色
            ColorStateList colorList = getResources().getColorStateList(R.color.radio_backgroud);
            radioButton.setTextColor(colorList);
            //设置字体大小
            radioButton.setTextSize(20);
            //设置文本内容
            radioButton.setText(list.get(i).name);
            //将控件放进group里面
            group.addView(radioButton);
        }
        group.invalidate();
    }

    /*
     * 定义加载fragment的方法
     */
    public ArrayList<Fragment> getFrag() {
        ArrayList<Fragment> list = new ArrayList<Fragment>();
        list.add(new ViewPagerFragment());
        list.add(new ViewPagerFragment());
        list.add(new ViewPagerFragment());
        list.add(new ViewPagerFragment());
        list.add(new ViewPagerFragment());
        list.add(new ViewPagerFragment());
        list.add(new ViewPagerFragment());
        list.add(new ViewPagerFragment());
        list.add(new ViewPagerFragment());
        list.add(new ViewPagerFragment());
        list.add(new ViewPagerFragment());
        return list;
    }

    /**
     * 初始化头部导航条
     */
    private void initView() {
        DisplayMetrics dm = new DisplayMetrics();
        getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
        indicatorWidth = dm.widthPixels / 4;
        //获取布局填充器
        mInflater = (LayoutInflater) getActivity().getSystemService(getActivity().LAYOUT_INFLATER_SERVICE);

        //设置适配器
        viewPager.setAdapter(new FragmentPagerAdapter(this.getChildFragmentManager()) {
            @Override
            public Fragment getItem(int position) {
                return frag.get(position);
            }

            @Override
            public int getCount() {
                return frag.size();
            }
        });

    }

}
